#include <string>
#include <set>
#include <iostream>
#include <cassert>
#include "MessageHadling.h"

using namespace std;

/********************	Class Message defination begin	********************/
Message::Message(string message) : content(message){}

Message::Message(const Message& message){
	content = message.content;
	folderPtr = message.folderPtr;
	set<Folder *>::iterator it = folderPtr.begin();
	while(it != folderPtr.end()){
		(*it)->messagePtr.insert(this);
		++it;
	}
}

Message::~Message(){
	std::cout << "Destruct Message: " << content << endl;
	/*for(set<Folder*>::iterator it = folderPtr.begin(); it != folderPtr.end(); it++){
		delete *it;
	}*/
	folderPtr.clear();
}

void Message::save(Folder *folder){
	folderPtr.insert(folder);
	folder->messagePtr.insert(this);
}

void Message::remove(Folder *folder){
	for(set<Folder*>::iterator it = folderPtr.begin(); it != folderPtr.end(); it++){
		/* delete *it; */
		folder->messagePtr.erase(this);
		// delete *it; // encounter an exception ??
	}
	/*delete this;*/
	/* folderPtr.clear();*/ // will cause error when release the second folder.
}

Message& Message::operator=(const Message& message){
	assert(&message != this);
	/*for(set<Folder*>::iterator it = folderPtr.begin(); it != folderPtr.end(); it++){		
		// delete *it;
		(*it)->messagePtr.erase(this);
	}*/
	folderPtr.clear();
	content = message.content;
	folderPtr = message.folderPtr;
	for(set<Folder*>::iterator it = folderPtr.begin(); it != folderPtr.end(); it++){		
		(*it)->messagePtr.insert(this);
	}
	return *this;
}
/********************	Class Message defination end	********************/


/********************	Class Folder defination begin	********************/
Folder::Folder(string name) : name(name){}

Folder::~Folder(){
	cout << "Destruct folder: " << name << endl;
	set<Message*>::iterator it = messagePtr.begin(); 
	while(it != messagePtr.end()){
		// delete *it; // will cause a infinite loop
		messagePtr.erase(*it);
		// ++ it;
	}
}
/********************	Class Folder defination end    ********************/